﻿using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using WPF.Common;

namespace TB4
{
    public class SelectorContextMenuItem : MenuItem
    {
        private Selector _selector;
        private ContextMenu _parentContextMenu;

        public SelectorContextMenuItem()
        {
            Loaded += (sender, args) =>  OnLoaded();
        }

        void OnLoaded()
        {
            _parentContextMenu = this.TryFindParent<ContextMenu>();
            
            _selector = _parentContextMenu.PlacementTarget is Selector ? (Selector) _parentContextMenu.PlacementTarget : _parentContextMenu.PlacementTarget.TryFindParent<Selector>();
        }

        protected override void OnClick()
        {
            _selector.SelectedItem = DataContext;
            base.OnClick();
        }
    }
}